package org.dromara.snailjob;

import com.aizuda.snailjob.server.common.rpc.server.grpc.GrpcServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.util.TimeZone;
import java.util.concurrent.TimeUnit;

/**
 * SnailJob Server 启动程序
 *
 * @author shuai.zhou
 * @date 2024-05-17
 */
@Slf4j
@EnableTransactionManagement(proxyTargetClass = true)
@SpringBootApplication(scanBasePackages = {"com.aizuda.snailjob.server.starter.*", "org.dromara.snailjob.config"})
public class SnailJobServerApplication {

    public static void main(String[] args) {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
        SpringApplication.run(SnailJobServerApplication.class, args);
        System.out.println("(♥◠‿◠)ﾉﾞ  SnailJob定时任务启动成功   ლ(´ڡ`ლ)ﾞ  ");
    }

    @Bean
    public ApplicationRunner grpcStartupChecker(GrpcServer grpcServer, ServletWebServerFactory serverFactory) {
        return args -> {
            // 最长自旋10秒，保证grpcServer启动完成
            int waitCount = 0;
            while (!grpcServer.isStarted() && waitCount < 100) {
                log.info("--------> snail-job grpc server is staring....");
                TimeUnit.MILLISECONDS.sleep(100);
                waitCount++;
            }

            if (!grpcServer.isStarted()) {
                log.error("--------> snail-job grpc server startup failure.");
                // Grpc启动失败，停止Web服务和Spring Boot应用程序
                serverFactory.getWebServer().stop();
                SpringApplication.exit(SpringApplication.run(SnailJobServerApplication.class));
            }
        };
    }

}
